package com.gitee.ywj1352.gasc.security;

import com.gitee.ywj1352.gasc.utils.ResponseUtils;
import com.gitee.ywj1352.gasc.pojo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * 权限 校验的 核心 sso
 */
@Component
@Slf4j
public class SSOAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.info("AdminAuthenticationProvider  ;;;;");
        // 获取前端表单中输入后返回的用户名、密码
        String token = (String) authentication.getPrincipal();
        String email;
        if (StringUtils.isBlank(email = verificationSso(token))) {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            ResponseUtils.out(response, Result.error("sso 校验 失败"));
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(email);
        return new UsernamePasswordAuthenticationToken(userDetails, "pwd", userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    private String verificationSso(String token) {
        log.info("校验sso");
        if ("123456".equals(token)){
            String email = "yangwenjie.a@yuewen.com";
            return email;
        }else if ("1234567".equals(token)){
            return "yangwenjie1.a@yuewen.com";
        }else {
            return null;
        }
    }
}
